import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xuance/RoutePath.dart';
import 'package:xuance/bean/AiWarningitemBean.dart';
import 'package:xuance/constant.dart';
import 'package:xuance/generated/assets.dart';
import 'package:xuance/page/warning_detail/logic.dart';
import 'package:xuance/util/ChartUtil.dart';
import 'package:xuance/util/common_util.dart';
import 'package:xuance/widget/CommonOutlinedButton.dart';
import 'package:xuance/widget/CustomProgressBar.dart';
import 'package:xuance/widget/EmptyWidget.dart';
import 'package:xuance/widget/WarningLevelWidget.dart';

import 'logic.dart';

class RuleWarnPage extends StatelessWidget {
  const RuleWarnPage({super.key});

  @override
  Widget build(BuildContext context) {
    final logic = Get.find<RuleWarnLogic>();
    final state = logic.state;
    return Scaffold(
        backgroundColor: bgColor,
        body: SafeArea(
            child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 13),
                child: Column(
                  children: [
                    Expanded(
                        child: SingleChildScrollView(
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                          Container(
                              padding: const EdgeInsets.all(15),
                              decoration: BoxDecoration(
                                  gradient: const LinearGradient(
                                      colors: [
                                        Color.fromARGB(25, 95, 215, 174),
                                        Color.fromARGB(10, 95, 215, 174)
                                      ],
                                      begin: Alignment.topCenter,
                                      end: Alignment.bottomCenter),
                                  borderRadius: BorderRadius.circular(5)),
                              child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Image.asset(Assets.assetsEventfeature,
                                        scale: 3),
                                    const SizedBox(height: 10),
                                    Padding(
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 10),
                                        child: Obx(() {
                                          if (state.eventFeatureList.isEmpty) {
                                            return const EmptyWidget();
                                          }
                                          return ListView.separated(
                                              shrinkWrap: true,
                                              physics:
                                                  const NeverScrollableScrollPhysics(),
                                              itemCount:
                                                  state.eventFeatureList.length,
                                              itemBuilder:
                                                  (BuildContext context,
                                                      int index) {
                                                var bean = state
                                                    .eventFeatureList[index];
                                                int total = state
                                                    .eventFeatureList
                                                    .map((m) =>
                                                        m.warningSum?.toInt() ??
                                                        0)
                                                    .reduce((a, b) => a + b)
                                                    .toInt();
                                                var percentage = ((bean
                                                            .warningSum
                                                            ?.toInt() ??
                                                        0) /
                                                    total);
                                                return Row(children: [
                                                  Expanded(
                                                      flex: 5,
                                                      child: CustomProgressBar(
                                                          height: 20,
                                                          backgroundColor:
                                                              Colors.grey
                                                                  .withAlpha(
                                                                      100),
                                                          progressColor:
                                                              bean.color,
                                                          progress:
                                                              percentage)),
                                                  const SizedBox(width: 10),
                                                  Expanded(
                                                      flex: 2,
                                                      child: Column(
                                                          crossAxisAlignment:
                                                              CrossAxisAlignment
                                                                  .start,
                                                          children: [
                                                            Text(
                                                                "${bean.warningFeature}",
                                                                maxLines: 1,
                                                                overflow:
                                                                    TextOverflow
                                                                        .ellipsis,
                                                                style: TextStyle(
                                                                    color: bean
                                                                        .color,
                                                                    fontSize:
                                                                        10)),
                                                            Text(
                                                                "${bean.warningSum}(${percentage.toStringAsFixed(2)}%)",
                                                                style: TextStyle(
                                                                    color: bean
                                                                        .color,
                                                                    fontSize:
                                                                        10))
                                                          ]))
                                                ]);
                                              },
                                              separatorBuilder:
                                                  (BuildContext context,
                                                      int index) {
                                                return const SizedBox(
                                                    height: 5);
                                              });
                                        }))
                                  ])),
                          const SizedBox(height: 15),
                          Container(
                              padding: const EdgeInsets.all(15),
                              decoration: BoxDecoration(
                                  gradient: const LinearGradient(
                                      colors: [
                                        Color.fromARGB(25, 95, 215, 174),
                                        Color.fromARGB(10, 95, 215, 174)
                                      ],
                                      begin: Alignment.topCenter,
                                      end: Alignment.bottomCenter),
                                  borderRadius: BorderRadius.circular(5)),
                              child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(children: [
                                      Expanded(
                                          child: Align(
                                              alignment: Alignment.centerLeft,
                                              child: Image.asset(
                                                  Assets.assetsTitleEvent,
                                                  scale: 3))),
                                      Obx(() {
                                        return CommonOutlinedButton(
                                          onTap: () {
                                            state.isEventChart.value = true;
                                            logic.getList(
                                                getTime(state.dateType.value));
                                          },
                                          active: state.isEventChart.value,
                                          title: '事件图表',
                                        );
                                      }),
                                      const SizedBox(width: 10),
                                      Obx(() {
                                        return CommonOutlinedButton(
                                          onTap: () {
                                            state.isEventChart.value = false;
                                            logic.getList(
                                                getTime(state.dateType.value));
                                          },
                                          active: !state.isEventChart.value,
                                          title: '实时列表',
                                        );
                                      })
                                    ]),
                                    const SizedBox(height: 10),
                                    Container(
                                        decoration: BoxDecoration(
                                            color: const Color(0xff24454C),
                                            borderRadius:
                                                BorderRadius.circular(5)),
                                        child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceAround,
                                            children: [
                                              Obx(() {
                                                return WarningLevelWidget(
                                                    title: "高危",
                                                    dividerColor: c_red,
                                                    value: state
                                                            .highList.isEmpty
                                                        ? "0"
                                                        : "${state.highList.map((m) => m.warningSum).reduce((a, b) => (int.tryParse('$a') ?? 0) + (int.tryParse('$b') ?? 0))}");
                                              }),
                                              Obx(() {
                                                return WarningLevelWidget(
                                                    title: "中危",
                                                    dividerColor: c_orange,
                                                    value: state
                                                            .mediumList.isEmpty
                                                        ? "0"
                                                        : "${state.mediumList.map((m) => m.warningSum).reduce((a, b) => (int.tryParse('$a') ?? 0) + (int.tryParse('$b') ?? 0))}");
                                              }),
                                              Obx(() {
                                                return WarningLevelWidget(
                                                    title: "低危",
                                                    dividerColor: c_blue,
                                                    value: state.lowList.isEmpty
                                                        ? "0"
                                                        : "${state.lowList.map((m) => m.warningSum).reduce((a, b) => (int.tryParse('$a') ?? 0) + (int.tryParse('$b') ?? 0))}");
                                              })
                                            ])),
                                    const SizedBox(height: 15),
                                    Obx(() {
                                      if (state.isEventChart.value) {
                                        return AspectRatio(
                                            aspectRatio: 1.4,
                                            child: Obx(() {
                                              if (state.allList.isEmpty) {
                                                return const EmptyWidget();
                                              }
                                              return LineChart(
                                                  ChartUtil.getMainMidChart(
                                                      low: state.lowList.value,
                                                      mid: state
                                                          .mediumList.value,
                                                      high:
                                                          state.highList.value,
                                                      type: state
                                                          .dateType.value));
                                            }));
                                      } else {
                                        return Column(children: [
                                          Obx(() {
                                            if (state.allList.isEmpty) {
                                              return const EmptyWidget();
                                            }
                                            return ListView.builder(
                                                shrinkWrap: true,
                                                physics:
                                                    const NeverScrollableScrollPhysics(),
                                                itemCount: state.allList.length,
                                                itemBuilder:
                                                    (BuildContext context,
                                                        int index) {
                                                  var bean =
                                                      state.allList[index];
                                                  return InkWell(
                                                    onTap: () {
                                                      Get.toNamed(
                                                          RoutePath
                                                              .warningDetail,
                                                          arguments:
                                                              TrafficDetailBean(
                                                            bean: AiWarningItemList(
                                                                sip: bean.sip,
                                                                dip: bean.dip,
                                                                dpt: bean.dpt,
                                                                spt: bean.spt,
                                                                startDate: bean
                                                                    .warnTime,
                                                                protocols: []),
                                                            isWarnDetail: false,
                                                            queryCondition: state
                                                                .queryCondition
                                                                .value,
                                                            type: state
                                                                .dateType.value,
                                                          ));
                                                    },
                                                    child: Container(
                                                        padding:
                                                            const EdgeInsets
                                                                .symmetric(
                                                                vertical: 10,
                                                                horizontal: 5),
                                                        decoration: BoxDecoration(
                                                            color: index %
                                                                        2 ==
                                                                    0
                                                                ? const Color(
                                                                    0xff233F48)
                                                                : Colors
                                                                    .transparent),
                                                        child: DefaultTextStyle(
                                                            style:
                                                                const TextStyle(
                                                                    color: Colors
                                                                        .white),
                                                            child: Column(
                                                                crossAxisAlignment:
                                                                    CrossAxisAlignment
                                                                        .start,
                                                                children: [
                                                                  Text(
                                                                      "时间:${bean.warnTime}"),
                                                                  Text(
                                                                      "类型:${bean.sceneType}"),
                                                                  Text(
                                                                      "流量:${bean.sip}:${bean.spt}->${bean.dip}:${bean.dpt}"),
                                                                ]))),
                                                  );
                                                });
                                          }),
                                          Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                              children: [
                                                GestureDetector(
                                                    onTap: logic.lastPage,
                                                    child: const Padding(
                                                        padding:
                                                            EdgeInsets.all(8.0),
                                                        child: Text("上一页",
                                                            style: TextStyle(
                                                                color: Color(
                                                                    0xff9EA1A6))))),
                                                Obx(() {
                                                  return Text(
                                                      "第${logic.page.value}页,共${state.pageSize.value}页",
                                                      style: const TextStyle(
                                                          color: Color(
                                                              0xff9EA1A6)));
                                                }),
                                                GestureDetector(
                                                    onTap: logic.nextPage,
                                                    child: Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                .all(8.0),
                                                        child: Text("下一页",
                                                            style: TextStyle(
                                                                color:
                                                                    c_green))))
                                              ])
                                        ]);
                                      }
                                    })
                                  ])),
                          const SizedBox(height: 15),
                          Container(
                              padding: const EdgeInsets.all(15),
                              decoration: BoxDecoration(
                                  gradient: const LinearGradient(
                                      colors: [
                                        Color.fromARGB(25, 95, 215, 174),
                                        Color.fromARGB(10, 95, 215, 174)
                                      ],
                                      begin: Alignment.topCenter,
                                      end: Alignment.bottomCenter),
                                  borderRadius: BorderRadius.circular(5)),
                              child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Image.asset(Assets.assetsDataStaticstic,
                                        scale: 3),
                                    const SizedBox(height: 10),
                                    SingleChildScrollView(
                                      scrollDirection: Axis.horizontal,
                                      child: Row(children: [
                                        Obx(() {
                                          return CommonOutlinedButton(
                                            onTap: () {
                                              state.groupWay.value = 1;
                                              logic.getStatisticData();
                                            },
                                            active: state.groupWay.value == 1,
                                            title: '攻击来源',
                                          );
                                        }),
                                        const SizedBox(width: 6),
                                        Obx(() {
                                          return CommonOutlinedButton(
                                              onTap: () {
                                                state.groupWay.value = 2;
                                                logic.getStatisticData();
                                              },
                                              active: state.groupWay.value == 2,
                                              title: '攻击目标');
                                        }),
                                        const SizedBox(width: 6),
                                        Obx(() {
                                          return CommonOutlinedButton(
                                              onTap: () {
                                                state.groupWay.value = 3;
                                                logic.getStatisticData();
                                              },
                                              active: state.groupWay.value == 3,
                                              title: '攻击来源端口');
                                        }),
                                        const SizedBox(width: 6),
                                        Obx(() {
                                          return CommonOutlinedButton(
                                              onTap: () {
                                                state.groupWay.value = 4;
                                                logic.getStatisticData();
                                              },
                                              active: state.groupWay.value == 4,
                                              title: '攻击目标端口');
                                        })
                                      ]),
                                    ),
                                    Container(
                                      padding: const EdgeInsets.symmetric(
                                          vertical: 8, horizontal: 3),
                                      child: DefaultTextStyle(
                                        style: TextStyle(color: c_9EA1A6),
                                        child: const Row(
                                          children: [
                                            Expanded(
                                                child:
                                                    Center(child: Text("NO"))),
                                            SizedBox(width: 10),
                                            Expanded(
                                                flex: 3,
                                                child: Center(
                                                    child: Text("Attack:"))),
                                            SizedBox(width: 10),
                                            Expanded(
                                                flex: 1,
                                                child: Center(
                                                    child: Text("Count"))),
                                            SizedBox(width: 10),
                                            Expanded(
                                                flex: 2,
                                                child: Center(
                                                    child: Text("Percent"))),
                                          ],
                                        ),
                                      ),
                                    ),
                                    Obx(() {
                                      if (state.statisticList.isEmpty) {
                                        return const EmptyWidget();
                                      }
                                      return ListView.builder(
                                          shrinkWrap: true,
                                          physics:
                                              const NeverScrollableScrollPhysics(),
                                          padding: EdgeInsets.zero,
                                          itemCount: state.statisticList.length,
                                          itemBuilder: (BuildContext context,
                                              int index) {
                                            var bean =
                                                state.statisticList[index];
                                            return Container(
                                                padding:
                                                    const EdgeInsets.symmetric(
                                                        vertical: 8,
                                                        horizontal: 3),
                                                color: index % 2 == 0
                                                    ? const Color(0xff233F48)
                                                    : Colors.transparent,
                                                child: DefaultTextStyle(
                                                    style: TextStyle(
                                                        color: c_9EA1A6),
                                                    child: Row(children: [
                                                      Expanded(
                                                          child: Center(
                                                        child: Text(
                                                            "${index + 1}"
                                                                .padLeft(
                                                                    2, "0")),
                                                      )),
                                                      const SizedBox(width: 10),
                                                      Expanded(
                                                        flex: 3,
                                                        child: Center(
                                                            child: Text(
                                                                bean.attackIp)),
                                                      ),
                                                      const SizedBox(width: 10),
                                                      Expanded(
                                                          flex: 1,
                                                          child: Center(
                                                            child: Text(
                                                                "${bean.list.length}"
                                                                    .padLeft(3,
                                                                        "0")),
                                                          )),
                                                      const SizedBox(width: 10),
                                                      Expanded(
                                                          flex: 2,
                                                          child: Center(
                                                              child: Text(
                                                                  "${((bean.list.length / state.statisticTotal.value) * 100).toStringAsFixed(3)}%")))
                                                    ])));
                                          });
                                    })
                                  ])),
                          const SizedBox(height: 15)
                        ])))
                  ],
                ))));
  }
}
